var express = require("express");
var router = express.Router();
const multer = require("multer");
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
var COS = require("cos-nodejs-sdk-v5");
var cos = new COS({
  SecretId: "AKIDnSu88wiaSEoAKJ6f070e3E9rKZhhU1Vp",
  SecretKey: "A6nFdzCDzYtzqa8RYS8YjpmYBbnkSvBF",
});
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

router.post("/", upload.single("file"), function (req, res, next) {
  // #swagger.tags = ['上传']
  // #swagger.summary = '通用上传文件接口'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */

  if (!req.file || req.file.length === 0) {
    res.status(400).send("文件为空");
  } else {
    let { folderPath } = req.query;
    let originalname = req.file.originalname;
    let file = req.file.buffer;
    cos.putObject(
      {
        Bucket: "jiangdutest-1307977142" /* 必须 */,
        Region: "ap-shanghai" /* 必须 */,
        Key:
          folderPath +
          "/" +
          new Date().valueOf() +
          "JD-BACKEND-" +
          originalname /* 必须 */,
        Body: file,
      },
      function (err, data) {
        if (err) {
          log.error(err);
        }
        if (data.statusCode == 200) {
          let response = {
            name: originalname,
            url: data.Location,
          };
          res.status(200).send(response);
        } else {
          res.status(500).send("上传失败");
        }
      }
    );
  }
});

module.exports = router;
